<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>edit_features</title>
    <script src="../../dist/openlayers/include-openlayers.js"></script>
    <style>
        .editPane {
            position: absolute;
            right: 65px;
            top: 8px;
            text-align: center;
            background: #FFF;
            z-index: 1000;
            border-radius: 4px;
        }

        .ol-popup {
            position: absolute;
            background-color: white;
            -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
            filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
            padding: 15px;
            border-radius: 10px;
            border: 1px solid #cccccc;
            bottom: 12px;
            left: -50px;
            min-width: 120px;
        }

        .ol-popup:after,
        .ol-popup:before {
            top: 100%;
            border: solid transparent;
            content: " ";
            height: 0;
            width: 0;
            position: absolute;
            pointer-events: none;
        }

        .ol-popup:after {
            border-top-color: white;
            border-width: 10px;
            left: 48px;
            margin-left: -10px;
        }

        .ol-popup:before {
            border-top-color: #cccccc;
            border-width: 11px;
            left: 48px;
            margin-left: -11px;
        }

        .tooltip {
            position: relative;
            background: rgba(0, 0, 0, 0.5);
            border-radius: 4px;
            color: white;
            padding: 4px 8px;
            opacity: 0.7;
            white-space: nowrap;
        }
    </style>
</head>

<body style=" margin: 0;overflow: hidden;background: #fff;width: 100%;height:100%; position: absolute;top: 0;">
    <div id="map" style="width: 100%;height:100%"></div>
    <div id="popup" class="ol-popup">
        <div id="popup-content"></div>
    </div>
    <div>
        <div class="panel panel-primary editPane" id="editPane">
            <div class='panel-heading'>
                <h5 class='panel-title text-center' data-i18n="resources.text_editSingle"></h5>
            </div>
            <div class='panel-body content'>
                <input type='button' class='btn btn-default' data-i18n="[value]resources.btn_addMarker"
                    onclick='addMarker()' />&nbsp;
                <input type='button' class='btn btn-default' data-i18n="[value]resources.btn_undoAdd"
                    onclick='revocationMarker()' />
                <input type='button' class='btn btn-default' data-i18n="[value]resources.text_input_value_submit"
                    onclick='commit()' />&nbsp;
                <input type='button' class='btn btn-default' data-i18n="[value]resources.text_input_value_clear"
                    onclick='clearLayer()' />
            </div>
        </div>
    </div>
    <script type="text/javascript" include="bootstrap,widgets.alert" src="../js/include-web.js"></script>
    <script type="text/javascript">
        var map, id = [], pointFeature, vectorSource, resultLayer, editFeaturesService, alertDiv,
            addPointsSource, addPointsLayer,
            baseUrl = "http://localhost:8090/iserver/services/map-Dubai/rest/maps/Dubai",
            url = "http://localhost:8090/iserver/services/data-Dubai/rest/data",
            container = document.getElementById('popup'),
            content = document.getElementById('popup-content'),
            overlay = new ol.Overlay(({
                element: container,
                autoPan: true,
                autoPanAnimation: {
                    duration: 250
                },
                offset: [0, -20]
            })),

            map = new ol.Map({
                target: 'map',
                controls: ol.control.defaults({ attributionOptions: { collapsed: false } })
                    .extend([new ol.supermap.control.Logo()]),
                view: new ol.View({
                    center: [55.23, 25.08], // 中心点
                    zoom: 12,
                    projection: 'EPSG:4326',
                    multiWorld: true
                }),
            });
        var layer = new ol.layer.Tile({
            source: new ol.source.TileSuperMapRest({
                url: baseUrl,
                tileLoadFunction: function (tile, src) {
                    var xhr = new XMLHttpRequest();
                    xhr.responseType = 'blob';
                    xhr.addEventListener('loadend', function (evt) {
                        var data = this.response;
                        if (data !== undefined) {
                            tile.getImage().src = URL.createObjectURL(data);
                        } else {
                            tile.setState('error');
                        }
                    });
                    xhr.addEventListener('error', function () {
                        tile.setState('error');
                    });
                    xhr.open('GET', src);
                    xhr.setRequestHeader('Accept', '*/*');
                    xhr.setRequestHeader('X-HW-ID', "userid");
                    xhr.setRequestHeader('X-HW-APPKEY', "username");
                    xhr.send();
                }
            }),
            projection: 'EPSG:4326'
        });
        map.addLayer(layer);

        //创建鼠标操作提示：
        var helpTooltipElement, helpTooltip, isclearPoint;

        createHelpTooltip();

        function createHelpTooltip() {
            if (helpTooltipElement) {
                helpTooltipElement.parentNode.removeChild(helpTooltipElement);
            }
            helpTooltipElement = document.createElement('div');
            helpTooltipElement.className = 'tooltip hidden';
            helpTooltip = new ol.Overlay({
                element: helpTooltipElement,
                offset: [15, 0],
                positioning: 'center-left'
            });
        }

        initFeature();
        loadLayer();

        function loadLayer() {
            //添加查询结果图层
            vectorSource = new ol.source.Vector({
                wrapX: false
            });
            resultLayer = new ol.layer.Vector({
                source: vectorSource,
            });

            //添加点图层
            addPointsSource = new ol.source.Vector({
                wrapX: false
            });
            addPointsLayer = new ol.layer.Vector({
                source: addPointsSource,
            });

            map.addLayer(addPointsLayer);
            map.addLayer(resultLayer);
        }

        editFeaturesService = new ol.supermap.FeatureService(url, {
            headers: {
                "X-HW-ID": "userid",
                "X-HW-APPKEY": "username"
            }
        });

        function initFeature() {
            var polygon = new ol.geom.Polygon([[[55, 25], [57, 25], [57, 28], [55, 28], [55, 20]]]);
            var featureService = new ol.supermap.FeatureService(url, {
                headers: {
                    "X-HW-ID": "userid",
                    "X-HW-APPKEY": "username"
                }
            });
            var getFeatureParams = new SuperMap.GetFeaturesByGeometryParameters({
                toIndex: -1,
                datasetNames: ["are-mupoi:areare___________pi"],
                geometry: polygon,
                spatialQueryMode: "INTERSECT"
            });
            featureService.getFeaturesByGeometry(getFeatureParams, function (serviceResult) {
                var features = (new ol.format.GeoJSON()).readFeatures(serviceResult.result.features);
                for (var i = 0; i < features.length; i++) {
                    features[i].setStyle(new ol.style.Style({
                        image: new ol.style.Icon(({
                            anchor: [0.5, 0.9],
                            src: '../img/markerbig_select.png'
                        }))
                    }));
                }

                //避免重复添加图层，只对一个图层进行数据更新操作：
                if (vectorSource.getFeatures().length > 0) {
                    vectorSource.clear();
                }
                vectorSource.addFeatures(features);

                map.on('pointermove', pointermoveLinstener);
            });
        }

        function pointermoveLinstener(e) {
            var select = false;
            map.forEachFeatureAtPixel(e.pixel, function (feature) {
                if (feature.getProperties().CAPITAL) {
                    map.getTargetElement().style.cursor = 'pointer';
                    var contentHTML = feature.getProperties().CAPITAL;
                    content.innerHTML = contentHTML;
                    overlay.setPosition(feature.getGeometry().getCoordinates());
                    map.addOverlay(overlay);
                    select = true
                }
            }, {
                hitTolerance: 10
            });
            if (!select) {
                map.getTargetElement().style.cursor = '';
                overlay.setPosition(undefined);
                map.removeOverlay(overlay);
            }
            if (isclearPoint) {
                helpTooltipElement.innerHTML = resources.text_selectMarkerToDelete;
                helpTooltip.setPosition(e.coordinate);
                helpTooltipElement.classList.remove('hidden');
                map.addOverlay(helpTooltip);
            } else {
                helpTooltip.setPosition(undefined);
                helpTooltipElement.classList.add('hidden');
            }
        }

        function addMarker() {
            if (isclearPoint) {
                closeSelectListener();
            }
            widgets.alert.clearAlert();
            var xmax = 55, xmin = 53, ymax = 22, ymin = 20,
                point = [Math.floor(Math.random() * (xmax - xmin + 1) + xmin), Math.floor(Math.random() * (ymax - ymin + 1) + ymin)];
            if (!pointFeature) {
                ceateMarker(point)
            } else {
                addPointsSource.clear();
                ceateMarker(point)
            }

            function ceateMarker(point) {
                pointFeature = new ol.Feature(new ol.geom.Point(point));
                pointFeature.setStyle(new ol.style.Style({
                    image: new ol.style.Circle({
                        fill: new ol.style.Fill({
                            color: [255, 0, 0, 0.5]
                        }),
                        stroke: new ol.style.Stroke({
                            color: 'red',
                            width: 2
                        }),
                        radius: 8
                    })
                }));
                pointFeature.setProperties({ TEL_TYPE: 1, NAME: 'zmm' });
                //判断添加点图层已添加到地图，避免重复添加图层，只对一个图层进行数据更新操作：
                addPointsSource.addFeature(pointFeature);
                map.getView().animate({
                    duration: 850,
                    zoom: 5,
                    center: point,
                });
            }
        }

        function revocationMarker() {
            if (isclearPoint) {
                closeSelectListener();
            }
            if (pointFeature) {
                addPointsSource.clear();
                pointFeature = null;
            } else {
                widgets.alert.showAlert(resources.msg_noRevocableMarker, false);
            }
        }

        function commit() {
            widgets.alert.clearAlert();
            if (isclearPoint) {
                closeSelectListener();
            }
            if (pointFeature) {
                var addFeatureParams = new SuperMap.EditFeaturesParameters({
                    features: pointFeature,
                    dataSourceName: "are-mupoi",
                    dataSetName: "areare___________pi",
                    editType: "add",
                    returnContent: true
                });
                editFeaturesService.editFeatures(addFeatureParams, function (serviceResult) {
                    if (serviceResult.result.succeed) {
                        id.push(serviceResult.result[0]);
                        addPointsSource.clear();
                        vectorSource.clear();
                        pointFeature = null;
                        initFeature();
                        widgets.alert.showAlert(resources.msg_submitSuccess, true);
                    }
                });
            } else {
                widgets.alert.showAlert(resources.msg_noMarkerToSubmit, false);
            }
        }

        function clearLayer() {
            widgets.alert.clearAlert();
            isclearPoint = true;
            map.on('click', selectListener);
        }

        function selectListener(e) {
            var deletedId = null;
            map.forEachFeatureAtPixel(e.pixel, function (feature) {
                //只删选中第一个要素：
                if (!deletedId) {
                    deletedId = feature.getId();
                    var deleteParams = new SuperMap.EditFeaturesParameters({
                        dataSourceName: "are-mupoi",
                        dataSetName: "areare___________pi",
                        IDs: [deletedId],
                        editType: "delete"
                    });

                    editFeaturesService.editFeatures(deleteParams, function (serviceResult) {
                        if (serviceResult.result.succeed) {
                            initFeature();
                            vectorSource.clear();
                            isclearPoint = false;
                            closeSelectListener();
                            widgets.alert.showAlert(resources.text_deleteSuccess, true);
                        } else {
                            widgets.alert.showAlert(resources.msg_deleteFailed, false)
                        }
                    });
                }
            }, {
                hitTolerance: 1
            });

        }

        function closeSelectListener() {
            isclearPoint = false;
            map.un('click', selectListener);
            helpTooltip.setPosition(undefined);
            map.removeOverlay(helpTooltip);
            helpTooltipElement.classList.add('hidden');
        }

    </script>
</body>

</html>